package com.google.jessewilson.codesearch.intellij.dnd;

import com.google.jessewilson.codesearch.ui.Clipboard;
import com.intellij.openapi.ide.CopyPasteManager;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author jessewilson
 */
public class IntelliJClipboard implements Clipboard {

  public boolean setContents(String text) {
    CopyPasteManager.getInstance().setContents(new StringSelection(text));
    return true;
  }

  public String getContents() {
    Transferable contents = CopyPasteManager.getInstance().getContents();
    if(!contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      return null;
    }

    try {
      return (String)contents.getTransferData(DataFlavor.stringFlavor);
    } catch(UnsupportedFlavorException e) {
      Logger.getLogger(IntelliJClipboard.class.getName())
          .log(Level.WARNING, "Failed to get clipboard contents", e);
      return null;
    } catch(IOException e) {
      Logger.getLogger(IntelliJClipboard.class.getName())
          .log(Level.WARNING, "Failed to get clipboard contents", e);
      return null;
    }
  }
}
